package br.com.sca.dao;

import java.io.Serializable;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public abstract class DAO implements Serializable {

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("sca");
    EntityManager em = emf.createEntityManager();

    public <T> void salvar(T entity) {
        try {
            em.getTransaction().begin();
            em.persist(entity);
            em.getTransaction().commit();
        } catch (Exception e) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
        }
    }

    public <T> void alterar(T entity) {
        try {
            em.getTransaction().begin();
            em.merge(entity);
            em.getTransaction().commit();
        } catch (Exception e) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
        }
    }

    public <T> void excluir(T entity) {
        try {
            em.getTransaction().begin();
            em.remove(entity);
            em.getTransaction().commit();
            System.out.println(">>>>>>>>>  Excluir Commit");
        } catch (Exception e) {
            System.out.println(">>>>>>>>>  Excluir Rollback");
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
        }
    }

    public <T> T carregar(Object key, Class<T> classe) {
        return em.find(classe, key);
    }

    protected Query criaQuery(String query) {
        return em.createQuery(query);
    }
}
